package logic

import (
	"context"
	"fmt"
	"math/rand"
	"time"
	"video-hub/models/cache"
	"video-hub/models/mysql"
	"video-hub/pkg"

	"video-hub/videorpc/internal/svc"
	"video-hub/videorpc/videorpc"

	"github.com/pkg/errors"
	"github.com/zeromicro/go-zero/core/logx"
	"gorm.io/gorm"
)

type RegisterLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewRegisterLogic(ctx context.Context, svcCtx *svc.ServiceContext) *RegisterLogic {
	return &RegisterLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *RegisterLogic) Register(in *videorpc.RegisterRequest) (*videorpc.RegisterResponse, error) {
	// todo: add your logic here and delete this line
	var user mysql.User

	result, _ := cache.Rdb.Get(l.ctx, "sendSms"+in.PhoneNum).Result()
	if result == "" {
		return nil, errors.New("短信验证码错误")
	}
	if err := user.FindPhone(mysql.DB, in.PhoneNum); err == nil {
		return nil, errors.New("该手机号已注册，可直接登录")
	}
	user = mysql.User{
		Model:      gorm.Model{},
		PhoneNum:   in.PhoneNum,
		Pwd:        pkg.Md5(in.Pwd),
		NickName:   fmt.Sprintf("游客%d%d", time.Now().Unix(), rand.Intn(100)),
		AvatarLink: "https://gips3.baidu.com/it/u=1148997845,2755062458&fm=3074&app=3074&f=PNG?w=2048&h=2048",
	}

	if err := user.AddUser(mysql.DB); err != nil {
		return nil, err
	}
	return &videorpc.RegisterResponse{
		UserId: int64(user.ID),
	}, nil
}
